import 'dart:io';

import 'package:image_picker/image_picker.dart';
import 'package:latlong2/latlong.dart';
import 'package:situation/app/router/router_name.dart';
import 'package:situation/data/request/base_request.dart';
import 'package:situation/data/request/intell_request.dart';
import 'package:situation/data/store/auth_store.dart';
import 'package:situation/domain/common/MapLatLonDto.dart';
import 'package:situation/domain/common/UploadImageDto.dart';
import 'package:situation/domain/intell/IntellAnnex.dart';
import 'package:situation/domain/intell/IntellArea.dart';
import 'package:situation/domain/intell/IntellCategory.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter_smart_dialog/flutter_smart_dialog.dart';
import 'package:get/get.dart';
import 'package:situation/shared/util/util_mk.dart';
import 'package:situation/shared/util/util_permission.dart';
import 'package:tdesign_flutter/src/components/cell/td_cell.dart';
import 'package:tdesign_flutter/tdesign_flutter.dart';
// import 'package:wechat_assets_picker/wechat_assets_picker.dart' hide LatLng;
// import 'package:wechat_camera_picker/wechat_camera_picker.dart' hide LatLng;

import 'state.dart';

class PublishIntellController extends GetxController {
  final PublishIntellState state = PublishIntellState();

  // 发布的类
  Map publishDto = Map();

  List<IntellArea> intellAreaList = [];

  TextEditingController typeController = TextEditingController();
  TextEditingController unitController = TextEditingController();
  TextEditingController phoneController = TextEditingController();
  TextEditingController detailController = TextEditingController();
  TextEditingController timeController = TextEditingController();

  @override
  void onInit() {
    // TODO: implement onInit
    super.onInit();
    IntellCategory arguments = Get.arguments;
    // 手机号自动获取
    if (AuthStore.to.isLogin) {
      phoneController.text = AuthStore.to.profile.mobile!;
    }

    publishDto['typeId'] = int.parse(arguments.id!);
    typeController.text = arguments.name!;

    var now = DateTime.now();
    state.upTime =
        '${now.year.toString().padLeft(4, '0')}-'
        '${now.month.toString().padLeft(2, '0')}-'
        '${now.day.toString().padLeft(2, '0')} '
        '${now.hour.toString().padLeft(2, '0')}:'
        '${now.minute.toString().padLeft(2, '0')}:'
        '${now.second.toString().padLeft(2, '0')}';
  }

  void publish() {
    publishDto['phone'] = phoneController.text;
    publishDto['detail'] = detailController.text;

    if (state.addressName == '') {
      SmartDialog.showNotify(msg: '请选择地理位置', notifyType: NotifyType.failure);
      return;
    }

    if (phoneController.text.isEmpty) {
      SmartDialog.showNotify(msg: '请输入手机号', notifyType: NotifyType.failure);
      return;
    }

    if (state.imgList.length == 0) {
      SmartDialog.showNotify(msg: '请至少上传1张图片', notifyType: NotifyType.failure);
      return;
    }
    var list = state.imgList;
    if (state.video.path != null) {
      list.add(state.video);
    }
    publishDto['annexs'] = list;
    IntellRequest.publishIntell(publishDto).then((value) {
      SmartDialog.showNotify(msg: '发布成功', notifyType: NotifyType.success);
      Get.back();
    });
  }

  // 地址选择
  Future<void> addressSelect(TDCell cell) async {
    MapLatLonDto mapLatLonDto = await Get.toNamed(RouterName.commonMapPointSelect);
    state.addressName = "${mapLatLonDto.address}";
    // 获取上报单位

    // 设置经纬度
    publishDto['lat'] = mapLatLonDto.lat.toString();
    publishDto['lon'] = mapLatLonDto.lon.toString();
    publishDto['position'] = state.addressName;
    publishDto['position'] = state.addressName;
    publishDto['areaCode'] = mapLatLonDto.streetCode;
  }

  void showUpTimeSelect(TDCell cell) {
    var now = DateTime.now();
    TDPicker.showDatePicker(
      Get.context,
      title: '选择时间',
      onConfirm: (selected) {
        state.upTime =
            '${selected['year'].toString().padLeft(4, '0')}-'
            '${selected['month'].toString().padLeft(2, '0')}-'
            '${selected['day'].toString().padLeft(2, '0')} '
            '${selected['hour'].toString().padLeft(2, '0')}:'
            '${selected['minute'].toString().padLeft(2, '0')}:'
            '${selected['second'].toString().padLeft(2, '0')}';
        Get.back();
      },
      useHour: true,
      useMinute: true,
      useSecond: true,
      initialDate: [
        now.year,
        now.month,
        now.day,
        now.hour,
        now.minute,
        now.second,
      ],
    );
  }

  void onFileAdd() async {
    await UtilPermission.requestCaremaPermission();

    int max = 9 - state.imgList.length;

    if (max == 0 && state.video.path != '') {
      SmartDialog.showNotify(
        msg: '最多上传9张图片和一个视频',
        notifyType: NotifyType.failure,
      );
      return;
    }
    final ImagePicker picker = ImagePicker();
    Get.bottomSheet(
      CupertinoActionSheet(
        actions: <Widget>[
          CupertinoActionSheetAction(
            child: const Text('拍照'),
            onPressed: () async {
              final XFile? photo = await picker.pickImage(source: ImageSource.camera);

              if (photo != null) {
                // 文件上传
                await upload(photo,"img");
              }
              Get.back();
            },
          ),
          CupertinoActionSheetAction(
            child: const Text('录像'),
            onPressed: () async {
              final XFile? photo = await picker.pickVideo(source: ImageSource.camera);

              if (photo != null) {
                // 文件上传
                await upload(photo,"video");
              }
              Get.back();
            },
          ),
          CupertinoActionSheetAction(
            child: const Text('从相册选择'),
            onPressed: () async {
              final XFile? image = await picker.pickMedia();
              if (image != null) {
                // 文件上传
                await upload(image,UtilMk.getFileType(image.path));
              } else {
                SmartDialog.showToast('未选择文件');
              }
              Get.back();
            },
          ),
        ],
        cancelButton: CupertinoActionSheetAction(
          child: const Text('取消'),
          onPressed: () {
            Get.back();
          },
        ),
      ),
    );
  }

  Future<void> upload(XFile entity,String type) async {

    SmartDialog.showLoading(msg: '上传中...');
    print("file.path" + entity.path);
    UploadImageDto uploadImageDto = await BaseRequest.uploadFile(entity.path);
    print("file.path 123" );
    var length =await  entity.length();

    // 通过文件路径截取文件名称
    if (type == "img") {
      state.imgList.add(
        IntellAnnex(
          name: entity.path.split("/").last,
          path: uploadImageDto.path,
          type: 1,
          size: length.toString(),
        ),
      );
      state.imgList = state.imgList.toList();
    } else {
      state.videoThumb = await UtilMk.getThumbnal(entity.path);
      UploadImageDto coverImg = await BaseRequest.uploadFile(state.videoThumb);

      state.video = IntellAnnex(
        name:  entity.path.split("/").last,
        path: uploadImageDto.path,
        type: 2,
        size: length.toString(),
        coverImg: coverImg.path,
      );
    }

    SmartDialog.dismiss();
  }

  void removeImg(i) {
    state.imgList.removeAt(i);
    state.imgList = state.imgList.toList();
  }
}
